package com.ecloud.scheduler.job;

import com.alibaba.fastjson.JSON;
import com.ecloud.client.HbaseClient;
import com.ecloud.client.TrendClient;
import com.ecloud.common.JsonResult;
import com.ecloud.common.ResultEnum;
import com.ecloud.common.exception.ServerException;
import com.ecloud.trend.vo.TdbEnvironmentPresentResult;
import com.ecloud.trend.vo.TdbEnvironmentPresentVo;
import com.ecloud.trend.vo.TdbPresentVo;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 实时数据
 *
 * @author Squbi
 */
@Component
public class PresentDataTransferJob implements SimpleJob {

    private static final Logger logger = LoggerFactory.getLogger(PresentDataTransferJob.class);

    @Autowired
    private HbaseClient hbaseClient;

    @Autowired
    private TrendClient trendClient;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        //获取触发器的名称及其组名称，获取作业详细信息的名称及其组名称.
        String triggerName = context.getTrigger().getKey().getName();
        String jobDetailName = context.getJobDetail().getKey().getName();
        logger.info("开始执行 {},触发器 {}", jobDetailName, triggerName);
        job();
    }

    public void job() {
        // 能量
        JsonResult jsonResult = trendClient.presentEnergy();
        logger.info("trend present energy : {}", jsonResult.toStringExData());
        List<TdbPresentVo> energyList = jsonResult.unpackArray(TdbPresentVo.class);
        logger.info("energy list length: {}", energyList.size());
        hbaseClient.postEnergyPresent(energyList).unwrap();
        // 控制
        jsonResult = trendClient.presentControl();
        logger.info("trend present control : {}", jsonResult.toStringExData());
        List<TdbPresentVo> controlList = jsonResult.unpackArray(TdbPresentVo.class);
        logger.info("control list length: {}", controlList.size());
        hbaseClient.postControlPresent(controlList).unwrap();
        // 环境
        jsonResult = trendClient.presentEnvironment();
        logger.info("trend present environment : {}", jsonResult.toStringExData());
        String json = JSON.toJSONString(jsonResult.getData());
        TdbEnvironmentPresentResult environmentResult = JSON.parseObject(json, TdbEnvironmentPresentResult.class);
        if (!environmentResult.isSuccess()) {
            throw new ServerException(ResultEnum.CALL_ERROR);
        }
        List<TdbEnvironmentPresentVo> environmentVos = environmentResult.getValues().getResult();
        logger.info("environment list length: {}", environmentVos.size());
        hbaseClient.postEnvironmentPresent(environmentVos).unwrap();
    }
}
